let _Vue = null

const HISTORY = 'history'
const HASH = 'hash'

export default class VueRouter {
  // 构造函数
  constructor (options) {
    this.options = options
    this.routeMap = {}
    // 调用这个方法来赋初值 防止刷新的时候 页面和url不对应
    const current = this.options.mode === HASH ? window.location.hash.slice(1) || '/' : window.location.pathname
    this.data = _Vue.observable({
      current: current
    })
  }

  createRouteMap () {
    /**
     * 遍历路由规则，并将路由规则解析成键值对存储到routeMap中
     */
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  // 静态的install方法
  static install (Vue) {
    /**
     * 判断当前插件是否已经安装
     * 把vue的构造函数记录到全局变量
     * 把创建vue实例时候传入的router对象注入到Vue实例
     */

    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true

    _Vue = Vue

    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  initComponents (Vue) {
    const that = this
    // 生成组件
    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h(
          'a',
          {
            attrs: {
              href: this.to
            },
            on: {
              click: this.clickHandler
            }
          },
          [this.$slots.default]
        )
      },
      methods: {
        clickHandler (e) {
          // 判断当前是什么路由模式
          switch (that.options.mode) {
            // hash模式
            case HASH:
              window.location.hash = this.to
              break
            // history模式
            case HISTORY:
              history.pushState({}, '#', this.to)
              this.$router.data.current = this.to
              break
            default :
              history.pushState({}, '#', this.to)
              this.$router.data.current = this.to
              break
          }
          // 阻止a标签的默认事件
          e.preventDefault()
        }
      }
    })

    const self = this
    // 渲染相应的组件
    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component)
      }
    })
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  initEvent () {
    // 监听popstate事件
    (this.options.mode === HISTORY || this.options.mode === undefined) && window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname
    })

    // 监听hash改变的时间并渲染相应的组件
    this.options.mode === HASH && window.addEventListener('hashchange', (e) => {
      this.data.current = window.location.hash.slice(1) || '/'
    })
  }
}
